package com.example.privacy;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;

import com.example.privacy.Utils.SharedPreferencesUtils;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//创建存储关键信息的记录，如果有就看是否完整，如果没有就创建
public class StartActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        if(SharedPreferencesUtils.getInstance(StartActivity.this).getString("token","").equals("")){
            System.out.println("未找到token");
            Intent i = new Intent(this, LoginActivity.class);
            startActivity(i);
            //跳转到登录界面
        }else{
            //找到token，说明也保存了username和password
            //测试接口验证token是否过期，过期就重新登录，拿着已有的username和password
           TestToken();
            //未过期就直接跳转到功能界面
        }
    }

    private void TestToken(){

        new Thread(new Runnable() {
            @Override
            public void run() {
                final MediaType JSON = MediaType.get("application/json; charset=utf-8");
                String url = getString(R.string.baseUrl)+"/authenticate";
                System.out.println(url);
                final OkHttpClient client = new OkHttpClient();
                RequestBody body = RequestBody.create(null,"");
                final Request request = new Request.Builder()
                        .url(url)
                        .addHeader("Authorization","Bearer "+SharedPreferencesUtils.getInstance(StartActivity.this).getString("token",""))
                        .post(body)
                        .build();
                try {
                    //判断请求是否成功，也就是判断登录是否成功
                    Response response = client.newCall(request).execute();
                    if(response.code()==200){
                        //如果token的用户名和已保存用户名一致，就成功，并跳转
                        if(SharedPreferencesUtils.getInstance(StartActivity.this).getString("useranme","").equals(response.body().string())){
                            //验证信息是否完整
                            Information();
                        }else{
                            //不一致，就清空以缓存的数据
                            SharedPreferencesUtils.getInstance(StartActivity.this).putString("username","");
                            SharedPreferencesUtils.getInstance(StartActivity.this).putString("password","");
                            SharedPreferencesUtils.getInstance(StartActivity.this).putString("token","");
                        }
                    }else{
                        //在这里自动登录保存并跳转
                        Authenticate(SharedPreferencesUtils.getInstance(StartActivity.this).getString("username",""),
                                SharedPreferencesUtils.getInstance(StartActivity.this).getString("password",""));
                    }

                }catch (Exception e){
                    System.out.println(e.getMessage().toString());
                }
            }
        }).start();
    }

    private void Authenticate(final String username, final String password){

        new Thread(new Runnable() {
            @Override
            public void run() {
                final MediaType JSON = MediaType.get("application/json; charset=utf-8");
                String url = getString(R.string.baseUrl)+"/authenticate";
                System.out.println(url);
                final OkHttpClient client = new OkHttpClient();
                String json = String.format("{\"username\":\"%s\",\"password\":\"%s\"}", username,password);
                System.out.println(json);
                RequestBody body = RequestBody.create(json, JSON);
                System.out.println(body.toString());
                final Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
//                Request request = new Request.Builder().url("https://baidu.com").build();
                System.out.println("运行");
                try {
                    //判断请求是否成功，也就是判断登录是否成功
                    Response response = client.newCall(request).execute();
                    if(response.code()==200){
//                        System.out.println("登录成功");
                        String result = response.body().string();
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("username",username);
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("password",password);
                        JSONObject jsonObject = new JSONObject(result);
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("token",jsonObject.getString("token"));
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("type",jsonObject.getString("type"));
                        Information();
                    }else{
//                        System.out.println("登录失败");
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("username","");
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("password","");
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("token","");
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("type","");
                    }
                    response.body().close();
                }catch (Exception e){
                    System.out.println(e.getMessage().toString());
                }
            }
        }).start();
    }

    private void Information(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = getString(R.string.baseUrl)+"/Information";
                System.out.println(url);
                final OkHttpClient client = new OkHttpClient();
                RequestBody body = RequestBody.create(null,"");
                System.out.println(body.toString());
                final Request request = new Request.Builder()
                        .url(url)
                        .addHeader("Authorization","Bearer "+SharedPreferencesUtils.getInstance(StartActivity.this).getString("token", ""))
                        .post(body)
                        .build();
                try {
                    //判断请求是否成功，也就是判断登录是否成功
                    Response response = client.newCall(request).execute();
                    if(response.code()==200){
                        if(response.body().string().equals("success")){
                            Thread.sleep(1000);
                            //这里根据type选择要去的页面
                            String type = SharedPreferencesUtils.getInstance(StartActivity.this).getString("type","");
                            if(type.equals("0")){
                                Intent i = new Intent(StartActivity.this,CustomerMenu.class);
                                startActivity(i);
                            }else if(type.equals("1")){
                                Intent i = new Intent(StartActivity.this, SenderMenu.class);
                                startActivity(i);
                            }else if(type.equals("2")){
                                Intent i = new Intent(StartActivity.this, DeliveryMenu.class);
                                startActivity(i);
                            }
                            StartActivity.this.finish();
                        }else{
                            Thread.sleep(1000);
                            Intent i = new Intent(StartActivity.this,InformationActivity.class);
                            startActivity(i);
                            StartActivity.this.finish();
                        }
                    }else{
                        //这里是请求失败，不允许登录，将登陆信息消除，并返回
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("username","");
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("password","");
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("token","");
                        SharedPreferencesUtils.getInstance(StartActivity.this).putString("type","");
                    }
                    response.body().close();
                }catch (Exception e){
                    System.out.println(e.getMessage().toString());
                }finally {

                }
            }
        }).start();
    }
}